document.addEventListener('DOMContentLoaded', function () {
    const registerForm = document.getElementById('registerForm');
    const errorMessage = document.getElementById('errorMessage');

    registerForm.addEventListener('submit', function (e) {
        e.preventDefault();

        // 获取表单值
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        const email = document.getElementById('email').value;

        // 前端验证
        if (!username || !password || !confirmPassword || !email) {
            showError('所有字段均为必填项');
            return;
        }

        if (password !== confirmPassword) {
            showError('密码和确认密码不一致');
            return;
        }

        // 发送注册请求到后端
        fetch('/api/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({username, password, email}),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('注册失败');
                }
                return response.json();
            })
            .then(data => {
                if (data && data.message) {
                    if (data.success) {
                        // 注册成功，重定向到登录页面
                        alert('注册成功，请登录');
                        window.location.href = 'login.html';
                    } else {
                        showError(data.message);
                    }
                } else {
                    showError('注册成功，请登录');
                    window.location.href = 'login.html';
                }
            })
            .catch(error => {
                showError('注册失败，请稍后再试');
            });
    });

    // 显示错误信息
    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
        setTimeout(() => {
            errorMessage.style.display = 'none';
        }, 5000);
    }
});